package com.example.music.fragment;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SearchView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.music.R;
import com.example.music.activity.MusicActivity;
import com.example.music.activity.MusicDemoActivity;
import com.example.music.adapter.IndexAdapter;
import com.example.music.adapter.SongAdapter;
import com.example.music.model.Song;
import com.example.music.utils.PinyinUtil;
import com.example.music.utils.SectionItemDecoration;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CategoryDetailFragment extends Fragment {
    private static final String TAG = "CategoryDetailFragment";
    private RecyclerView recyclerView;
    private RecyclerView indexRecyclerView;
    private SongAdapter songAdapter;
    private IndexAdapter indexAdapter;
    private List<Song> songList = new ArrayList<>();
    private Map<Integer, String> sectionMap = new HashMap<>();

    public enum CategoryType { BY_ALBUM, BY_ARTIST, BY_FOLDER }

    // 构造函数用于按分类显示歌曲
    public static CategoryDetailFragment newInstance(CategoryType categoryType, String categoryName) {
        CategoryDetailFragment fragment = new CategoryDetailFragment();
        Bundle args = new Bundle();
        args.putSerializable("category_type", categoryType);
        args.putString("category_name", categoryName);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_songs, container, false);
        recyclerView = view.findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        indexRecyclerView = view.findViewById(R.id.index_recycler_view);
        indexRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        // 加载本地歌曲并按规则排序
        loadSongs();

        // 搜索功能
        SearchView searchView = view.findViewById(R.id.search_view);
        if (searchView != null) {
            searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                @Override
                public boolean onQueryTextSubmit(String query) {
                    return false;
                }

                @Override
                public boolean onQueryTextChange(String newText) {
                    songAdapter.getFilter().filter(newText);
                    updateSectionMap();
                    indexAdapter.notifyDataSetChanged();
                    return true;
                }
            });
        } else {
            Log.e(TAG, "SearchView not found in the layout");
        }

        return view;
    }

    private void loadSongs() {
        CategoryType categoryType = (CategoryType) getArguments().getSerializable("category_type");
        String categoryName = getArguments().getString("category_name");

        try (Cursor cursor = requireContext().getContentResolver().query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                new String[]{
                        MediaStore.Audio.Media.TITLE,
                        MediaStore.Audio.Media.ARTIST,
                        MediaStore.Audio.Media.ALBUM,
                        MediaStore.Audio.Media.DATA,
                        MediaStore.Audio.Media.DURATION
                },
                MediaStore.Audio.Media.IS_MUSIC + " != 0",
                null,
                null
        )) {
            if (cursor == null) {
                Log.e(TAG, "Failed to get cursor");
                return;
            }

            while (cursor.moveToNext()) {
                String title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
                String artist = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
                String album = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
                String filePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
                long duration = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION));

                Song song = new Song(title, artist, album, filePath);
                song.setDuration(duration);

                // 获取专辑封面
                Bitmap albumCover = getAlbumArt(filePath);
                song.setAlbumCover(albumCover);

                if (isMatched(song, categoryType, categoryName)) {
                    songList.add(song);
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "Error loading songs", e);
        }

        // 中文拼音排序
        Collections.sort(songList, Comparator.comparing(song -> PinyinUtil.toPinyin(song.getTitle())));

        // 更新节索引映射
        updateSectionMap();

        // 设置Adapter
        songAdapter = new SongAdapter(songList);
        songAdapter.setOnItemClickListener(new SongAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(Song song) {
                Intent intent = new Intent(requireContext(), MusicDemoActivity.class);
                intent.putExtra("position", String.valueOf(songList.indexOf(song)));
                intent.putExtra("songList", new ArrayList<>(songList)); // Pass a copy of the list
                startActivity(intent);
            }
        });
        recyclerView.setAdapter(songAdapter);

        // 添加节索引装饰
        SectionItemDecoration decoration = new SectionItemDecoration(50, 30, new SectionItemDecoration.SectionCallback() {
            @Override
            public String getSectionHeader(int position) {
                return sectionMap.getOrDefault(position, "");
            }
        });
        recyclerView.addItemDecoration(decoration);

        // 初始化字母索引适配器
        String[] alphabet = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
        indexAdapter = new IndexAdapter(alphabet);
        indexAdapter.setOnItemClickListener(letter -> {
            for (int i = 0; i < songList.size(); i++) {
                if (sectionMap.containsKey(i) && sectionMap.get(i).equals(letter)) {
                    recyclerView.scrollToPosition(i);
                    break;
                }
            }
        });
        indexRecyclerView.setAdapter(indexAdapter);
    }

    private void updateSectionMap() {
        sectionMap.clear();
        char lastChar = '\0';
        for (int i = 0; i < songList.size(); i++) {
            String title = songList.get(i).getTitle();
            String pinyinTitle = PinyinUtil.toPinyin(title);
            if (!pinyinTitle.isEmpty()) {
                char firstChar = Character.toUpperCase(pinyinTitle.charAt(0));
                if (firstChar != lastChar) {
                    sectionMap.put(i, String.valueOf(firstChar));
                    lastChar = firstChar;
                }
            }
        }
    }

    private Bitmap getAlbumArt(String filePath) throws IOException {
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            retriever.setDataSource(filePath);
            byte[] artBytes = retriever.getEmbeddedPicture();
            if (artBytes != null) {
                return BitmapFactory.decodeByteArray(artBytes, 0, artBytes.length);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            retriever.release();
        }
        return null;
    }

    private boolean isMatched(Song song, CategoryType type, String categoryName) {
        switch (type) {
            case BY_ALBUM:
                return song.getAlbum().equals(categoryName);
            case BY_ARTIST:
                return song.getArtist().equals(categoryName);
            case BY_FOLDER:
                File file = new File(song.getPath());
                return file.getParent().equals(categoryName);
            default:
                return false;
        }
    }
}